/*
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

/* Author: Jorge Peña */

#include "xrandr-engine.h"
#include <stdlib.h>
#include <QProcess>
#include <QFile>
 
#include <Plasma/DataContainer>

using namespace std;
 
XRandREngine::XRandREngine(QObject* parent, const QVariantList& args)
    : Plasma::DataEngine(parent, args)
      , maxW(0)
      , maxH(0)
{
    // We ignore any arguments - data engines do not have much use for them
    Q_UNUSED(args)
 
    // This prevents applets from setting an unnecessarily high
    // update interval and using too much CPU.
    // In the case of a clock that only has second precision,
    // a third of a second should be more than enough.
    setMinimumPollingInterval(1000);
}

void XRandREngine::init(){
    xrandr = new QProcess(this);
    connect (xrandr, SIGNAL(finished(int,QProcess::ExitStatus)),
                this, SLOT(parseOutput()));
}
 
bool XRandREngine::sourceRequestEvent(const QString &name)
{
    // We do not have any special code to execute the
    // first time a source is requested, so we just call
    // updateSourceEvent().
    return updateSourceEvent(name);
}
 
bool XRandREngine::updateSourceEvent(const QString &name)
{
    if (name == I18N_NOOP("Screens")){
        xrandr->start("xrandr", QStringList() << "-q");
        xrandr->waitForFinished();
        numScreens = 0;
        QString id = "";
        foreach(Screen screen, screens){
            setData(name, screen.type, screen.state);
            numScreens += screen.state;
            if (id != ""){
                id += "#";
            }
            //if (screen.id != ""){
                id += screen.type + ":" + screen.id;
            //}
        }
        setData(name, I18N_NOOP("Identifier"),id);
        setData(name, I18N_NOOP("Detected Screens"), numScreens);
    }else if(name == I18N_NOOP("Virtual Desktop")){
        xrandr->start("xrandr", QStringList() << "-q");
        xrandr->waitForFinished();
        setData(name,I18N_NOOP("Width"),maxW);
        setData(name,I18N_NOOP("Height"),maxH);
        /*
        QFile file("/etc/X11/xorg.conf");
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            return false;

        while (!file.atEnd()) {
            QString line = file.readLine();
            if( line.contains("Virtual")){
                QStringList sizes = line.split(QRegExp("\\s+"),QString::SkipEmptyParts);
                setData(name,I18N_NOOP("Width"),sizes[1]);
                setData(name,I18N_NOOP("Height"),sizes[2]);
            }
        }
        */
    }
    return true;
}

void XRandREngine::parseOutput() {
    QByteArray bytes = xrandr->readAllStandardOutput();
    QStringList lines = QString(bytes).split("\n");
    screens.clear();
    QStringListIterator line(lines);
    QStringList sizes = line.next().split(QRegExp("\\s+"),QString::SkipEmptyParts);
    maxW = sizes[sizes.size()-3].toInt();
    maxH = sizes[sizes.size()-1].toInt();
    while (line.hasNext()){
        if (line.peekNext().contains("connected",Qt::CaseInsensitive)) {
            Screen s;
            s.type = line.peekNext().split(QRegExp("\\s+"),QString::SkipEmptyParts)[0];
            s.state = line.next().contains("disconnected",Qt::CaseInsensitive)?0:1;
            while(s.state && line.hasNext() && 
                    !line.peekNext().contains("connected",Qt::CaseInsensitive)
                    && line.peekNext() != ""){
                if(s.id != "") s.id += "-";
                s.id += line.next().split(QRegExp("\\s+"),QString::SkipEmptyParts)[0];
            }
            screens.push_back(s);
        }else{
            line.next();
        }
    }
}
 
// This does the magic that allows Plasma to load
// this plugin.  The first argument must match
// the X-Plasma-EngineName in the .desktop file.
K_EXPORT_PLASMA_DATAENGINE(testtime, XRandREngine)
 
// this is needed since XRandREngine is a QObject
#include "xrandr-engine.moc"
